package com.liu.case2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class SocketReceiver implements Runnable {

    DatagramSocket socket = null;
    private Integer port;
    private final String receiver;

    public SocketReceiver(Integer port, String receiver) {

        this.port = port;
        this.receiver = receiver;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        Boolean flag = true;

        while (true) {

            try {
                byte[] database = new byte[1024];
                DatagramPacket packet = new DatagramPacket(database, 0, database.length);
                socket.receive(packet);

                if (flag) {
                    System.out.println("\033[1;93;45m" + "对方在线中" + "\033[m");
                    flag = false;
                }

                String Data = new String(packet.getData(), 0, packet.getLength());
                if (Data.equals("End!")) {
                    System.err.println("对方已离线");
                    break;
                } else
                    System.out.println(receiver + ":" + Data);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        socket.close();
    }
}
